#pragma once
#include"common.hpp"
#include"Socket.hpp"

using fun_t = std::function<void(std::shared_ptr<TcpSocket> stcp,Inetaddr& addr)>;

class Tcpserver{

    void servetask(std::shared_ptr<TcpSocket> stcp, Inetaddr& addr)
    {   
        _fun(stcp,addr);
    }

public:
    Tcpserver(const int& port,fun_t fun)
    :_fun(fun),
    tcpser(std::make_unique<TcpSocket>()),
    _isrunning(false)
    {
        tcpser->BuideTcpSocket(port);
    }

    void Start()
    {
        _isrunning = true;
        while(true)
        {
            Inetaddr peer;
            int fd = tcpser->Accept(&peer);
            LOG(level::DEBUG)<<peer.String_addr();
            std::shared_ptr<TcpSocket> socketfd = std::make_shared<TcpSocket>(fd);
            pid_t id = fork();
            if(id < 0){
                LOG(level::ERROR)<<"fork false";
                exit(FORK_ERR);
            }
            else if(id == 0){
                close(tcpser->Getfd());
                if(fork() > 0)//子进程
                    exit(SUCCESS);
                //孙子进程
                servetask(socketfd,peer);
                close(fd);
                exit(SUCCESS);
            }
            else{
                close(fd);
                pid_t fathid = waitpid(id,nullptr,0);
                exit(SUCCESS);
            }
        }
        _isrunning = false;
    }

    ~Tcpserver(){}

private:
    std::unique_ptr<TcpSocket> tcpser;

    bool _isrunning;
    fun_t _fun;
};



























        // char buff[1024];
        // while(true)
        // {
        //     ssize_t rsz = read(sfd,buff,sizeof(buff));
        //     if(rsz > 0){
        //         buff[rsz] = 0;
        //         std::cout<<buff<<std::endl;
        //         _fun(sfd,addr);

        //     }
        //     else if(rsz == 0){
        //         close(sfd);
        //         LOG(level::INFO)<<"进程退出....";
        //         break;
        //     }
        //     else{
        //         close(sfd);
        //         LOG(level::ERROR)<<"读取异常....";
        //         break;
        //     }
        // }